package com.dsjy.yf.address.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsjy.yf.address.entity.dataobject.CountyDO;
import com.dsjy.yf.address.entity.myenum.OperateEnum;
import com.dsjy.yf.address.mapper.CountyMapper;
import com.dsjy.yf.address.service.CountyService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

/**
 * @author whj
 * @version 1.0
 * @date 2021-01-14 14:50
 */
@Service
@CacheConfig(cacheNames = "county")
public class CountyServiceImpl implements CountyService {

    @Resource
    private CountyMapper countyMapper;


    @Override
    public Integer searchMaxCountyCode() {
        return countyMapper.serchMaxCountyCode();
    }

    @Override
    @Cacheable(key = "'searchAll'")
    public List<CountyDO> searchAll() {
        return countyMapper.searchAll();
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @CacheEvict(key = "'searchAll'")
    public Integer addUpdDel(String operate, CountyDO countyDO) {
        Integer result = null;
        if (OperateEnum.ADD.getOperate().equals(operate) && countyDO.getCountyName() != null) {
            result = addCounty(countyDO);
        } else if (OperateEnum.UPDATE.getOperate().equals(operate) && countyDO.getId() != null) {
            result = updCounty(countyDO);
        }
        return result;
    }


    @Override
    public Integer addCounty(CountyDO countyDO) {
        Integer maxCountyCode = searchMaxCountyCode();
        if (maxCountyCode != null) {
            countyDO.setCountyCode(++maxCountyCode);
            countyDO.setCreateTime(new Timestamp(System.currentTimeMillis()));
            return countyMapper.addCounty(countyDO);
        }
        return null;
    }

    @Override
    public Integer updCounty(CountyDO countyDO) {
        countyDO.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        return countyMapper.updCounty(countyDO);
    }

    @Override
    public IPage searchWithPage(Integer pageNum, Integer pageSize, Boolean isAdmin, QueryWrapper wrapper) {
        wrapper.setEntityClass(CountyDO.class);
        if (isAdmin) {
            wrapper.isNotNull("create_time");
        }
        Page<CountyDO> page = new Page<>(pageNum, pageSize);
        return countyMapper.selectPage(page, wrapper);
    }
}
